package com.example.eshop_ssm.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.db.Session;
import com.example.eshop_ssm.entity.TbAdminUserInfo;
import com.example.eshop_ssm.service.LoginAndOutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/LoginAndOutController")
public class LoginAndOutController {
    @Autowired
    private LoginAndOutService loginAndOutService;
    public static String ADMINUSER = "adminUser";//session保存的用户信息标识名
    /**
     * 验证登录信息,此处是restful风格，无value值
     * @param userName
     * @param userPwd
     * @param code
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST)
    public void login(@RequestParam("username") String userName,
                      @RequestParam("password") String userPwd,
                      @RequestParam(value = "remeberMe",required = false) Integer isRemeberMe,
                      @RequestParam("code") String code,
                      HttpServletResponse response,
                      HttpServletRequest request) throws Exception {
        String md5Hex1 = DigestUtil.md5Hex( DigestUtil.md5Hex(userPwd));//两次MD5加密密码
        TbAdminUserInfo adminUser = loginAndOutService.loginVerification(userName,md5Hex1 ,code);
        //获取当前的验证码进行比较
        String lineCode = (String) request.getSession().getAttribute("lineCode");

        if (!lineCode.equalsIgnoreCase(code) || adminUser==null){
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println("<script>alert('输入信息有误错误！');location.href='/eshop_ssm/LoginAndOutController/reforwd';</script>");
            return;
        }else {
            //添加用户信息至session
            request.getSession().setAttribute(ADMINUSER,adminUser);
            //设置7天登录
            if (isRemeberMe!=null && isRemeberMe==1){
                Integer adminUserId1 = adminUser.getAdminUserId();
                //保存用户id到cookie
                Cookie adminUserId = new Cookie("adminUserId", adminUserId1.toString());
                adminUserId.setMaxAge(60*60*24*7);
                adminUserId.setPath("/");
                response.addCookie(adminUserId);
            }

            //跳转到用户登录前想要跳转的页面
            String requestURI = (String) request.getSession().getAttribute("forwardURL");
            if (requestURI!=null){
                response.sendRedirect(requestURI);
            }
            request.getRequestDispatcher("WEB-INF/jsp/index.jsp").forward(request,response);
        }
    }

    /**
     * 显示验证码
     * @param response
     * @throws Exception
     */
    @RequestMapping("/picCode")
    public void picCode(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);

        request.getSession().setAttribute("lineCode",lineCaptcha.getCode());
        lineCaptcha.write(response.getOutputStream());
    }

    /**
     * 跳转登录
     * @return
     * @throws Exception
     */
    @RequestMapping("/reforwd")
    public ModelAndView reforwd() throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }

    /**
     * 跳转首页
     * @return
     * @throws Exception
     */
    @RequestMapping("/index")
    public ModelAndView index() throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }

    /**
     * 退出登录
     * @param response
     * @return
     */
    @RequestMapping("loginOut")
    public ModelAndView loginOut(HttpServletRequest request,HttpServletResponse response){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");

        //清除cookie
        Cookie adminUserId = new Cookie("adminUserId", 0+"");
        adminUserId.setMaxAge(0);
        adminUserId.setPath("/");
        response.addCookie(adminUserId);

        //清除session
        request.getSession().removeAttribute(ADMINUSER);
        return modelAndView;
    }
}
